package com.zhonggong.network.service.impl;

import com.zhonggong.network.dao.FileIO;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class FileIOImpl implements FileIO {

	Connection conn;
	PreparedStatement st;
	ResultSet rs;
	private String driver;
	private String url;
	private String user;
	private String pass;

	public FileIOImpl() throws FileNotFoundException, IOException, ClassNotFoundException {
		this.initParam("mysql.ini");
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, user, pass);
			st = conn.prepareStatement("INSERT INTO T_STUDENTS VALUE(NULL,?,?,?)");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void initParam(String paramfile) throws FileNotFoundException, IOException {
		Properties props = new Properties();
		props.load(new FileInputStream(paramfile));
		driver = props.getProperty("driver");
		url = props.getProperty("url");
		user = props.getProperty("user");
		pass = props.getProperty("pass");
	}

	@Override
	public void leadingIn(String fileName) throws FileNotFoundException {

		File file = new File(fileName);
		InputStream input = new FileInputStream(file);
		XSSFWorkbook wb = null;
		try {
			wb = new XSSFWorkbook(input);
		} catch (IOException e) {
			e.printStackTrace();
		}
		XSSFSheet sheet = wb.getSheetAt(1);
		try {
			for (int i = 1; i <= sheet.getLastRowNum(); i++) {
				Row row = sheet.getRow(i);
				for (int j = 0; j < row.getLastCellNum(); j++) {
					Cell cell = row.getCell(j);
					if (cell != null) {
						cell.setCellType(CellType.STRING);
						String value = String.valueOf(row.getCell(j).getStringCellValue());
						if (j == 0)
							st.setString(j+2, value);
						if (j == 1)
							st.setString(j+2, value);
						if (j == 2)
							st.setString(j-1, value);
					}
				}
				st.executeUpdate();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (st != null) {
					st.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void leadingOut(String fileName) {
		// TODO Auto-generated method stub

	}
}
